#!/bin/bash

# OpenCloudOS 简化安装脚本
# 专门适配腾讯云 OpenCloudOS 系统，不依赖 EPEL

set -e

# 配置变量
PROJECT_NAME="tetris-game"
PROJECT_DIR="/opt/jpom/projects/${PROJECT_NAME}"
WEBHOOK_PORT="9999"
APP_PORT="3000"
GIT_REPO="https://gitee.com/cailei/tetris-game.git"  # 请替换为您的仓库地址

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 日志函数
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
    exit 1
}

# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then
    error "请使用 root 用户运行此脚本"
fi

log "🚀 开始配置 OpenCloudOS 服务器环境..."

# 1. 检查系统版本
log "📋 检查系统信息..."
if [ -f /etc/os-release ]; then
    . /etc/os-release
    log "系统: $NAME $VERSION"
fi

# 2. 更新系统
log "📦 更新系统包..."
dnf update -y

# 3. 安装基础软件 (只使用系统仓库)
log "🔧 安装基础软件..."
dnf install -y \
    curl \
    wget \
    git \
    python3 \
    python3-pip \
    nginx \
    firewalld \
    net-tools \
    vim \
    tar \
    gzip \
    unzip

# 4. 安装 Docker (使用官方脚本)
log "🐳 安装 Docker..."
if ! command -v docker &> /dev/null; then
    log "下载 Docker 安装脚本..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    log "执行 Docker 安装..."
    sh get-docker.sh
    rm -f get-docker.sh
else
    log "Docker 已安装，跳过..."
fi

# 5. 启动 Docker 服务
log "🐳 配置 Docker 服务..."
systemctl start docker
systemctl enable docker
usermod -aG docker $USER

# 6. 安装 Docker Compose (使用二进制文件)
log "🐳 安装 Docker Compose..."
if ! command -v docker-compose &> /dev/null; then
    log "下载 Docker Compose 二进制文件..."
    DOCKER_COMPOSE_VERSION="2.20.0"
    curl -L "https://github.com/docker/compose/releases/download/v${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose

    # 验证安装
    if docker-compose --version; then
        log "✅ Docker Compose 安装成功"
    else
        warn "❌ Docker Compose 安装失败，但不影响主要功能"
    fi
else
    log "Docker Compose 已安装，跳过..."
fi

# 7. 安装 Python 依赖
log "🐍 安装 Python 依赖..."
pip3 install flask

# 8. 创建项目目录
log "📁 创建项目目录..."
mkdir -p "${PROJECT_DIR}"
mkdir -p /var/log

# 9. 克隆项目代码 (如果提供了仓库地址)
log "📥 准备项目代码..."
cd "${PROJECT_DIR}"

# 创建基本的项目文件结构
log "📝 创建基本项目文件..."

# 创建 Dockerfile
cat > Dockerfile << 'EOF'
# 多阶段构建 - 构建阶段
FROM node:18-alpine AS builder

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build

# 生产阶段
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
EOF

# 创建构建脚本
cat > jpom-build.sh << 'EOF'
#!/bin/bash
set -e

PROJECT_NAME="tetris-game"
DOCKER_IMAGE_NAME="tetris-game"
DOCKER_CONTAINER_NAME="tetris-game"
DOCKER_PORT="3000"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

log "🚀 开始构建部署..."

# 停止旧容器
if docker ps -a --format 'table {{.Names}}' | grep -q "^${DOCKER_CONTAINER_NAME}$"; then
    docker stop "${DOCKER_CONTAINER_NAME}" || true
    docker rm "${DOCKER_CONTAINER_NAME}" || true
fi

# 删除旧镜像
if docker images --format 'table {{.Repository}}' | grep -q "^${DOCKER_IMAGE_NAME}$"; then
    docker rmi "${DOCKER_IMAGE_NAME}" || true
fi

# 构建新镜像
log "🔨 构建 Docker 镜像..."
docker build -t "${DOCKER_IMAGE_NAME}:latest" .

# 启动新容器
log "🚀 启动新容器..."
docker run -d \
    --name "${DOCKER_CONTAINER_NAME}" \
    --restart unless-stopped \
    -p "${DOCKER_PORT}:80" \
    "${DOCKER_IMAGE_NAME}:latest"

log "✅ 部署完成！访问地址: http://82.157.51.127:${DOCKER_PORT}"
EOF

chmod +x jpom-build.sh

# 创建 Webhook 接收器
cat > webhook-receiver.py << 'EOF'
#!/usr/bin/env python3
import json
import subprocess
import os
from flask import Flask, request, jsonify
import logging

logging.basicConfig(level=logging.INFO)
app = Flask(__name__)

BUILD_SCRIPT_PATH = "/opt/jpom/projects/tetris-game/jpom-build.sh"

@app.route('/webhook/gitee', methods=['POST'])
def gitee_webhook():
    try:
        data = request.get_json()
        logging.info(f"收到 Webhook: {data.get('hook_name', 'unknown')}")
        
        if data.get('hook_name') == 'push_hooks':
            logging.info("触发构建...")
            result = subprocess.run([BUILD_SCRIPT_PATH], capture_output=True, text=True, timeout=600)
            
            if result.returncode == 0:
                return jsonify({"message": "Build successful"}), 200
            else:
                return jsonify({"error": "Build failed", "output": result.stderr}), 500
        
        return jsonify({"message": "Not a push event"}), 200
    except Exception as e:
        logging.error(f"错误: {str(e)}")
        return jsonify({"error": str(e)}), 500

@app.route('/health', methods=['GET'])
def health():
    return jsonify({"status": "healthy"}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9999, debug=False)
EOF

chmod +x webhook-receiver.py

# 创建服务文件
cat > webhook-receiver.service << 'EOF'
[Unit]
Description=Tetris Game Webhook Receiver
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/jpom/projects/tetris-game
ExecStart=/usr/bin/python3 /opt/jpom/projects/tetris-game/webhook-receiver.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

# 10. 配置防火墙
log "🔥 配置防火墙..."
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-port=${WEBHOOK_PORT}/tcp
firewall-cmd --permanent --add-port=${APP_PORT}/tcp
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 11. 配置 Nginx
log "🌐 配置 Nginx..."
systemctl start nginx
systemctl enable nginx

# 创建 Nginx 配置
cat > /etc/nginx/conf.d/tetris-webhook.conf << 'EOF'
server {
    listen 80;
    server_name _;
    
    # Webhook 接收器
    location /webhook/ {
        proxy_pass http://127.0.0.1:9999;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    
    # 游戏应用
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    
    # 健康检查
    location /health {
        proxy_pass http://127.0.0.1:9999/health;
        access_log off;
    }
}
EOF

nginx -t && systemctl reload nginx

# 12. 配置 Webhook 服务
log "⚙️ 配置 Webhook 服务..."
cp webhook-receiver.service /etc/systemd/system/
systemctl daemon-reload
systemctl enable webhook-receiver
systemctl start webhook-receiver

# 13. 等待服务启动
log "⏳ 等待服务启动..."
sleep 5

# 14. 检查服务状态
log "📊 检查服务状态..."
echo ""
echo "=== 服务状态检查 ==="
systemctl is-active docker && echo "✅ Docker: 运行中" || echo "❌ Docker: 未运行"
systemctl is-active nginx && echo "✅ Nginx: 运行中" || echo "❌ Nginx: 未运行"
systemctl is-active webhook-receiver && echo "✅ Webhook: 运行中" || echo "❌ Webhook: 未运行"
systemctl is-active firewalld && echo "✅ 防火墙: 运行中" || echo "❌ 防火墙: 未运行"

# 15. 测试 Docker
log "🧪 测试 Docker..."
docker --version
docker run --rm hello-world && log "✅ Docker 测试成功" || warn "❌ Docker 测试失败"

# 16. 显示配置信息
echo ""
log "✅ OpenCloudOS 服务器配置完成！"
echo ""
echo "📋 配置信息:"
echo "  服务器IP: 82.157.51.127"
echo "  项目目录: ${PROJECT_DIR}"
echo "  Webhook端口: ${WEBHOOK_PORT}"
echo "  应用端口: ${APP_PORT}"
echo ""
echo "🌐 访问地址:"
echo "  健康检查: http://82.157.51.127/health"
echo "  Webhook URL: http://82.157.51.127/webhook/gitee"
echo ""
echo "🔧 下一步操作:"
echo "1. 将您的项目代码复制到: ${PROJECT_DIR}"
echo "2. 在项目目录中运行: npm install && npm run build"
echo "3. 执行构建: ./jpom-build.sh"
echo "4. 在 Gitee 中配置 Webhook: http://82.157.51.127/webhook/gitee"
echo ""
echo "📝 查看日志:"
echo "  Webhook 日志: journalctl -u webhook-receiver -f"
echo "  Nginx 日志: tail -f /var/log/nginx/error.log"
echo "  Docker 日志: docker logs tetris-game"
echo ""
echo "🎉 基础环境配置完成！"
